/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RecepcionReencauche.java
 *
 * Created on 19-jun-2012, 17:19:06
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.Categorias;
import com.camachosanchez.bean.ControlReencauche;
import com.camachosanchez.bean.DetalleControlReencauche;
import com.camachosanchez.bean.EstadosMedicion;
import com.camachosanchez.bean.EstadosNeumaticos;
import com.camachosanchez.bean.Neumaticos;
import com.camachosanchez.controler.jdbc.ControlReencaucheJdbcControler;
import com.camachosanchez.controler.jpa.CategoriasJpaController;
import com.camachosanchez.controler.jpa.EstadosMedicionJpaController;
import com.camachosanchez.gui.combo.WideComboBoxEditor;
import com.camachosanchez.gui.combo.WideComboBoxRenderer;
import com.camachosanchez.gui.table.ModeloTablaReencauche;
import com.camachosanchez.gui.table.RenderizadorTabla;
import com.camachosanchez.gui.table.RenderizadorTablaRecepcionMarcado;
import com.camachosanchez.gui.table.TableSorter;
import com.camachosanchez.gui.textfield.MaxLengthTextDocument;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.GUIUtil;
import com.camachosanchez.util.JPAUtil;
import java.awt.CardLayout;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.swing.BorderFactory;
import javax.swing.DefaultCellEditor;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import net.coderazzi.filters.gui.TableFilterHeader;

/**
 *
 * @author Rolando
 */
public class RecepcionReencauche extends javax.swing.JDialog implements MouseListener {

    private EntityManagerFactory emf = null;
    private ModeloTablaReencauche modelo;
    private TableFilterHeader filterHeader;
    private TableSorter tableSorter;
    private DefaultTableModel dm;
    private CardLayout card;
    private ControlReencauche controlReencauche;
    private JTextField textComentario;
    private HashMap<String, Short> hm = new HashMap<String, Short>();
    private List<String> descripcionCategorias;
    private HashMap<String, Short> hmEstados = new HashMap<String, Short>();
    private List<String> descripcionEstados;

    /** Creates new form RecepcionReencauche */
    public RecepcionReencauche(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.emf = JPAUtil.getEntityManagerFactory();
        setSize(700, 350);
        card = (CardLayout) pnlContenedor.getLayout();
        GUIUtil.addEscapeKey(this);
        modelo = new ModeloTablaReencauche();
        tableSorter = new TableSorter(modelo, tabla.getTableHeader());
        tabla.setModel(tableSorter);
        filterHeader = new TableFilterHeader();
        filterHeader.setTable(tabla);
        RenderizadorTabla render = new RenderizadorTabla();
        tabla.setDefaultRenderer(String.class, render);
        RenderizadorTablaRecepcionMarcado render2 = new RenderizadorTablaRecepcionMarcado(jTableDetalle.getTableHeader().getDefaultRenderer());
        llenarTabla();
        CategoriasJpaController emc = new CategoriasJpaController(null);
        List<Categorias> listaCategorias = emc.findCategoriasEntities();
        descripcionCategorias = new ArrayList<String>();
        if (listaCategorias != null) {
            for (Categorias item : listaCategorias) {
                if(item.getId().equals(Constantes.CATEGORIA_BODEGA) || item.getId().equals(Constantes.CATEGORIA_CEMENTERIO) || item.getId().equals(Constantes.CATEGORIA_STOCK) || item.getId().equals(Constantes.CATEGORIA_EN_DEVOLUCION)){
                    hm.put(item.getNombre(), item.getId().shortValue());
                    descripcionCategorias.add(item.getNombre());
                }
            }
        }
        EstadosMedicionJpaController dao = new EstadosMedicionJpaController(null);
        List<EstadosMedicion>  listaEstados = dao.findEstadosMedicionEntities();
        descripcionEstados = new ArrayList<String>();
        if (listaEstados != null) {
            for (EstadosMedicion estadosMedicion : listaEstados) {
                hmEstados.put(estadosMedicion.getNombre(), estadosMedicion.getId());
                descripcionEstados.add(estadosMedicion.getNombre());
            }
        }
        jTableDetalle.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        dm = new DefaultTableModel() {

            @Override
            public boolean isCellEditable(int row, int col) {
                if (col == 4 || col == 5 || col == 6 || col == 7) {
                    return true;
                }
                return false;
            }

            @Override
            public Class getColumnClass(int c) {
                if (c == 4) {
                    return Boolean.class;
                }
                return String.class;
            }
        };
        Object[] columns = new Object[]{"CÓDIGO", "NUEVA BANDA", "NUEVO PISO", "GARANTÍA", "RECEPCIÓN", "ESTADO", "DESTINO", "OBSERVACIONES"};
        dm.setColumnIdentifiers(columns);
        jTableDetalle.setModel(dm);
        jTableDetalle.setDefaultRenderer(String.class, render2);
        jTableDetalle.getColumnModel().getColumn(4).setCellRenderer(render2);
        this.setLocationRelativeTo(null);
        GUIUtil.SetAnchoColumnas(jTableDetalle);
        establecerEventosTeclas();
        MaxLengthTextDocument docNroFactura = new MaxLengthTextDocument();
        docNroFactura.setMaxChars(30, Constantes.ANY);
        txtNroFactura.setDocument(docNroFactura);
        jDateFechaRec.setMaxSelectableDate(new Date());
    }

    private void establecerEventosTeclas() {
        textComentario = new JTextField();
        TableColumn columnaCodigo = jTableDetalle.getColumnModel().getColumn(7);
        textComentario.addMouseListener(this);
        textComentario.setBorder(BorderFactory.createEmptyBorder());
        DefaultCellEditor singleclickCodigo = new DefaultCellEditor(
                textComentario);
        singleclickCodigo.setClickCountToStart(1);
        columnaCodigo.setCellEditor(singleclickCodigo);
    }

    private void setColumnaOculta() {
        tabla.getColumnModel().getColumn(3).setMinWidth(0);
        tabla.getColumnModel().getColumn(3).setMaxWidth(0);
        tabla.getColumnModel().getColumn(3).setPreferredWidth(0);
        tabla.getColumnModel().getColumn(7).setMinWidth(0);
        tabla.getColumnModel().getColumn(7).setMaxWidth(0);
        tabla.getColumnModel().getColumn(7).setPreferredWidth(0);
    }

    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlContenedor = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jPanel3 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabla = new javax.swing.JTable();
        jPanel7 = new javax.swing.JPanel();
        jPanel8 = new javax.swing.JPanel();
        jButton6 = new javax.swing.JButton();
        jButton7 = new javax.swing.JButton();
        jButton8 = new javax.swing.JButton();
        jPanel9 = new javax.swing.JPanel();
        jLabel13 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTableDetalle = new javax.swing.JTable();
        jPanel5 = new javax.swing.JPanel();
        jPanel6 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        lblDireccion = new javax.swing.JLabel();
        jPanel14 = new javax.swing.JPanel();
        jPanel10 = new javax.swing.JPanel();
        lblNumGuia = new javax.swing.JLabel();
        lblFecha = new javax.swing.JLabel();
        jPanel11 = new javax.swing.JPanel();
        txtNroGuia = new javax.swing.JTextField();
        txtFecha = new javax.swing.JTextField();
        jPanel17 = new javax.swing.JPanel();
        jPanel18 = new javax.swing.JPanel();
        txtDistribuidor = new javax.swing.JTextField();
        jPanel19 = new javax.swing.JPanel();
        lblTelefono = new javax.swing.JLabel();
        txtTelefono = new javax.swing.JTextField();
        txtDireccion = new javax.swing.JTextField();
        jPanel12 = new javax.swing.JPanel();
        jPanel15 = new javax.swing.JPanel();
        jButton10 = new javax.swing.JButton();
        jButton11 = new javax.swing.JButton();
        jButton12 = new javax.swing.JButton();
        jPanel16 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        txtNroFactura = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jDateFechaRec = new com.toedter.calendar.JDateChooser();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(".:: Recepción de Neumáticos Reencauchados ::.");
        setMinimumSize(new java.awt.Dimension(345, 380));
        setResizable(false);

        pnlContenedor.setLayout(new java.awt.CardLayout());

        jPanel2.setLayout(new java.awt.BorderLayout());

        jButton2.setText("<< Anterior");
        jButton2.setEnabled(false);
        jPanel3.add(jButton2);

        jButton3.setText("Siguiente >>");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton3);

        jButton4.setText("Finalizar");
        jButton4.setEnabled(false);
        jPanel3.add(jButton4);

        jPanel2.add(jPanel3, java.awt.BorderLayout.PAGE_END);

        jPanel4.setMaximumSize(new java.awt.Dimension(2147483647, 420));
        jPanel4.setMinimumSize(new java.awt.Dimension(23, 420));
        jPanel4.setPreferredSize(new java.awt.Dimension(452, 380));
        jPanel4.setLayout(new java.awt.BorderLayout());

        tabla.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tabla.setGridColor(new java.awt.Color(153, 153, 153));
        tabla.setRowHeight(22);
        tabla.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(tabla);

        jPanel4.add(jScrollPane1, java.awt.BorderLayout.CENTER);

        jPanel2.add(jPanel4, java.awt.BorderLayout.CENTER);

        pnlContenedor.add(jPanel2, "card2");

        jPanel7.setLayout(new java.awt.BorderLayout());

        jButton6.setText("<< Anterior");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel8.add(jButton6);

        jButton7.setText("Siguiente >>");
        jButton7.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton7ActionPerformed(evt);
            }
        });
        jPanel8.add(jButton7);

        jButton8.setText("Finalizar");
        jButton8.setEnabled(false);
        jPanel8.add(jButton8);

        jPanel7.add(jPanel8, java.awt.BorderLayout.PAGE_END);

        jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel13.setText("<html><font color='red'>(*)</font> Los neumáticos no seleccionados serán enviados a reclamo.</html>");
        jLabel13.setPreferredSize(new java.awt.Dimension(60, 14));

        jTableDetalle.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTableDetalle.setRowHeight(22);
        jScrollPane2.setViewportView(jTableDetalle);

        jPanel5.setLayout(new java.awt.BorderLayout(4, 4));

        jPanel6.setLayout(new java.awt.GridLayout(2, 1, 4, 4));

        jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLabel5.setText("Distribuidor:");
        jPanel6.add(jLabel5);

        lblDireccion.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        lblDireccion.setText("Dirección:");
        jPanel6.add(lblDireccion);

        jPanel5.add(jPanel6, java.awt.BorderLayout.LINE_START);

        jPanel14.setMinimumSize(new java.awt.Dimension(200, 100));
        jPanel14.setPreferredSize(new java.awt.Dimension(200, 100));
        jPanel14.setLayout(new java.awt.BorderLayout());

        jPanel10.setPreferredSize(new java.awt.Dimension(45, 48));
        jPanel10.setLayout(new java.awt.GridLayout(2, 1, 2, 4));

        lblNumGuia.setText("Guía Nº:");
        jPanel10.add(lblNumGuia);

        lblFecha.setText("Fecha:");
        jPanel10.add(lblFecha);

        jPanel14.add(jPanel10, java.awt.BorderLayout.LINE_START);

        jPanel11.setLayout(new java.awt.GridLayout(2, 1, 2, 4));

        txtNroGuia.setEditable(false);
        txtNroGuia.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtNroGuia.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel11.add(txtNroGuia);

        txtFecha.setEditable(false);
        txtFecha.setHorizontalAlignment(javax.swing.JTextField.CENTER);
        txtFecha.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel11.add(txtFecha);

        jPanel14.add(jPanel11, java.awt.BorderLayout.CENTER);

        jPanel5.add(jPanel14, java.awt.BorderLayout.LINE_END);

        jPanel17.setLayout(new java.awt.GridLayout(2, 1, 4, 4));

        jPanel18.setLayout(new java.awt.GridLayout(1, 3, 4, 4));

        txtDistribuidor.setEditable(false);
        txtDistribuidor.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        txtDistribuidor.setMaximumSize(new java.awt.Dimension(180, 23));
        txtDistribuidor.setMinimumSize(new java.awt.Dimension(180, 23));
        txtDistribuidor.setPreferredSize(new java.awt.Dimension(160, 23));
        jPanel18.add(txtDistribuidor);

        jPanel19.setLayout(new java.awt.BorderLayout(4, 4));

        lblTelefono.setText("Teléfono:");
        jPanel19.add(lblTelefono, java.awt.BorderLayout.LINE_START);

        txtTelefono.setEditable(false);
        txtTelefono.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        txtTelefono.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        txtTelefono.setMaximumSize(new java.awt.Dimension(120, 23));
        txtTelefono.setMinimumSize(new java.awt.Dimension(120, 23));
        txtTelefono.setPreferredSize(new java.awt.Dimension(100, 23));
        jPanel19.add(txtTelefono, java.awt.BorderLayout.CENTER);

        jPanel18.add(jPanel19);

        jPanel17.add(jPanel18);

        txtDireccion.setEditable(false);
        txtDireccion.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        txtDireccion.setMaximumSize(new java.awt.Dimension(205, 23));
        txtDireccion.setMinimumSize(new java.awt.Dimension(205, 23));
        txtDireccion.setPreferredSize(new java.awt.Dimension(205, 23));
        jPanel17.add(txtDireccion);

        jPanel5.add(jPanel17, java.awt.BorderLayout.CENTER);

        javax.swing.GroupLayout jPanel9Layout = new javax.swing.GroupLayout(jPanel9);
        jPanel9.setLayout(jPanel9Layout);
        jPanel9Layout.setHorizontalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 651, Short.MAX_VALUE)
                    .addComponent(jLabel13, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 651, Short.MAX_VALUE)
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 651, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel9Layout.setVerticalGroup(
            jPanel9Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel9Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel13, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 335, Short.MAX_VALUE))
        );

        jPanel7.add(jPanel9, java.awt.BorderLayout.CENTER);

        pnlContenedor.add(jPanel7, "card3");

        jPanel12.setLayout(new java.awt.BorderLayout());

        jButton10.setText("<< Anterior");
        jButton10.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton10ActionPerformed(evt);
            }
        });
        jPanel15.add(jButton10);

        jButton11.setText("Siguiente >>");
        jButton11.setEnabled(false);
        jPanel15.add(jButton11);

        jButton12.setText("Finalizar");
        jButton12.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton12ActionPerformed(evt);
            }
        });
        jPanel15.add(jButton12);

        jPanel12.add(jPanel15, java.awt.BorderLayout.PAGE_END);

        jLabel3.setText("Número de Factura:");

        txtNroFactura.setPreferredSize(new java.awt.Dimension(150, 20));

        jLabel7.setText("Fecha de Recepción:");

        jLabel9.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel9.setText("DATOS FINALES DE RECEPCIÓN");

        jDateFechaRec.setDateFormatString("dd/MM/yyyy");

        javax.swing.GroupLayout jPanel16Layout = new javax.swing.GroupLayout(jPanel16);
        jPanel16.setLayout(jPanel16Layout);
        jPanel16Layout.setHorizontalGroup(
            jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel16Layout.createSequentialGroup()
                .addGap(192, 192, 192)
                .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jSeparator1)
                    .addGroup(jPanel16Layout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtNroFactura, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel16Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jDateFechaRec, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jLabel9, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(219, Short.MAX_VALUE))
        );

        jPanel16Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel3, jLabel7});

        jPanel16Layout.setVerticalGroup(
            jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel16Layout.createSequentialGroup()
                .addContainerGap(169, Short.MAX_VALUE)
                .addComponent(jLabel9)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(9, 9, 9)
                .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(txtNroFactura, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel16Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel7, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jDateFechaRec, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(154, 154, 154))
        );

        jPanel12.add(jPanel16, java.awt.BorderLayout.CENTER);

        pnlContenedor.add(jPanel12, "card4");

        getContentPane().add(pnlContenedor, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
// TODO add your handling code here:
    int row = tabla.getSelectedRow();
    if (row > -1) {
        int value = Integer.parseInt(modelo.getValueAt(row, 7).toString());
        card.show(pnlContenedor, "card3");
        llenarPanelRecepcion(value);
    }
}//GEN-LAST:event_jButton3ActionPerformed

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
// TODO add your handling code here:
    card.show(pnlContenedor, "card2");
}//GEN-LAST:event_jButton6ActionPerformed

    private void jButton10ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton10ActionPerformed
        // TODO add your handling code here:
        card.show(pnlContenedor, "card3");
    }//GEN-LAST:event_jButton10ActionPerformed

    private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
        // TODO add your handling code here:
        card.show(pnlContenedor, "card4");
    }//GEN-LAST:event_jButton7ActionPerformed

    private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed
        // TODO add your handling code here:
        GuardarRecepcion();
    }//GEN-LAST:event_jButton12ActionPerformed
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton10;
    private javax.swing.JButton jButton11;
    private javax.swing.JButton jButton12;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton6;
    private javax.swing.JButton jButton7;
    private javax.swing.JButton jButton8;
    private com.toedter.calendar.JDateChooser jDateFechaRec;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel10;
    private javax.swing.JPanel jPanel11;
    private javax.swing.JPanel jPanel12;
    private javax.swing.JPanel jPanel14;
    private javax.swing.JPanel jPanel15;
    private javax.swing.JPanel jPanel16;
    private javax.swing.JPanel jPanel17;
    private javax.swing.JPanel jPanel18;
    private javax.swing.JPanel jPanel19;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JPanel jPanel6;
    private javax.swing.JPanel jPanel7;
    private javax.swing.JPanel jPanel8;
    private javax.swing.JPanel jPanel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable jTableDetalle;
    private javax.swing.JLabel lblDireccion;
    private javax.swing.JLabel lblFecha;
    private javax.swing.JLabel lblNumGuia;
    private javax.swing.JLabel lblTelefono;
    private javax.swing.JPanel pnlContenedor;
    private javax.swing.JTable tabla;
    private javax.swing.JTextField txtDireccion;
    private javax.swing.JTextField txtDistribuidor;
    private javax.swing.JTextField txtFecha;
    private javax.swing.JTextField txtNroFactura;
    private javax.swing.JTextField txtNroGuia;
    private javax.swing.JTextField txtTelefono;
    // End of variables declaration//GEN-END:variables

    private void llenarTabla() {
        modelo.limpiar();
        ControlReencaucheJdbcControler daoJdbc = new ControlReencaucheJdbcControler();
        List<ControlReencauche> registros = daoJdbc.findEnvios();
        for (ControlReencauche control : registros) {
            modelo.agregarRegistro(control);
        }
        jTableDetalle.getTableHeader().setReorderingAllowed(false);
        GUIUtil.SetAnchoColumnas(tabla);
        setColumnaOculta();
    }

    private void limpiarTabla() {
        while (dm.getRowCount() != 0) {
            dm.removeRow(0);
        }
    }

    private void llenarPanelRecepcion(int row) {
        this.limpiarTabla();
        ControlReencaucheJdbcControler daoJdbc = new ControlReencaucheJdbcControler();
        controlReencauche = daoJdbc.find(row);
        txtDireccion.setText(controlReencauche.getDireccion());
        txtDistribuidor.setText(controlReencauche.getIdDistribuidorNeumaticos().getNombre());
        Format formatter;
        formatter = new SimpleDateFormat("dd/MM/yyyy");
        String fecha = formatter.format(controlReencauche.getFechaEnvio());
        txtFecha.setText(fecha);
        txtTelefono.setText(controlReencauche.getTelefono());
        txtNroGuia.setText("Nº " + controlReencauche.getNumGuiaRemision());
        List<DetalleControlReencauche> detalle = controlReencauche.getDetalleControlReencaucheList();
        int filaDm = 0;
        for (DetalleControlReencauche item : detalle) {
            if(item.getFechaRecepcion() == null && item.getEstado()){// para los neumáticos aún no recepcionados y no cancelados
                Object[] fila = new Object[8];
                fila[0] = item.getIdNeumatico().getCodigo();
                fila[1] = item.getIdNuevoTipoBanda().getNombre();
                fila[2] = item.getIdNuevoTipoPiso().getNombre();
                fila[3] = (item.getPorGarantia()) ? "√" : "";
                fila[4] = Boolean.TRUE;
                if (descripcionEstados != null && !descripcionEstados.isEmpty()) {
                    fila[5] = descripcionEstados.get(0);
                } else {
                    fila[5] = "";
                }
                if (descripcionCategorias != null && !descripcionCategorias.isEmpty()) {
                    fila[6] = descripcionCategorias.get(0);
                } else {
                    fila[6] = "";
                }
                if (item.getObservacionesRecepcion() != null) {
                    fila[7] = item.getObservacionesRecepcion();
                } else {
                    fila[7] = "";
                }
                dm.addRow(fila);
                filaDm++;
            }
        }
        TableColumn col5 = jTableDetalle.getColumnModel().getColumn(5);
        col5.setCellEditor(new WideComboBoxEditor(descripcionEstados));
        col5.setCellRenderer(new WideComboBoxRenderer(descripcionEstados));
        
        TableColumn col6 = jTableDetalle.getColumnModel().getColumn(6);
        col6.setCellEditor(new WideComboBoxEditor(descripcionCategorias));
        col6.setCellRenderer(new WideComboBoxRenderer(descripcionCategorias));
    }

    private boolean ValidarDatos() {
        if (txtNroFactura.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Se requiere el número de factura.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
            txtNroFactura.requestFocusInWindow();
            return false;
        } else if (this.jDateFechaRec.getDate() == null) {
            JOptionPane.showMessageDialog(this, "Se requiere la fecha de recepción de reencauche.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
            jDateFechaRec.requestFocusInWindow();
            return false;
        }
        return true;
    }

    private void GuardarRecepcion() {
        if (ValidarDatos()) {
            EntityManager em = null;
            try {
                em = emf.createEntityManager();
                EntityTransaction tx = em.getTransaction();
                tx.begin();
                int fila = 0;
                ControlReencauche controlReencaucheRec = (ControlReencauche) em.getReference(ControlReencauche.class, controlReencauche.getId());
                if(jDateFechaRec.getDate().after(controlReencaucheRec.getFechaEnvio())){
                    List<DetalleControlReencauche> detalle = controlReencaucheRec.getDetalleControlReencaucheList();
                    for (DetalleControlReencauche item : detalle) {
                        if(item.getFechaRecepcion() == null && item.getEstado()){
                            item.setObservacionesRecepcion(dm.getValueAt(fila, 7).toString());
                            Neumaticos neumatico = (Neumaticos) em.getReference(Neumaticos.class, item.getIdNeumatico().getId());
                            if (Boolean.parseBoolean(dm.getValueAt(fila, 4).toString())) {//si es recepcionado
                                Categorias categoriaNueva = new Categorias(hm.get(dm.getValueAt(fila, 6).toString()).intValue());
                                neumatico.setIdCategoria(categoriaNueva);
                                EstadosMedicion estadoNuevo = new EstadosMedicion(hmEstados.get(dm.getValueAt(fila, 5).toString()).shortValue());
                                neumatico.setIdEstadoMedicion(estadoNuevo);
                                if(categoriaNueva.getId() == Constantes.CATEGORIA_EN_DEVOLUCION){
                                    neumatico.setFechaDevolucion(jDateFechaRec.getDate());
                                }
                                neumatico.setNumRenovaciones(neumatico.getNumRenovaciones() + 1);//aumenta el número de renovaciones
                                neumatico.setIdBanda(item.getIdNuevoTipoBanda());//cambia el neumático a su nuevo tipo de banda reencauchado
                                neumatico.setTipoPiso(item.getIdNuevoTipoPiso());
                                neumatico.setIdEstado(new EstadosNeumaticos(Constantes.ESTADO_RENOVADA));
                                item.setFechaRecepcion(jDateFechaRec.getDate());
                                item.setNumFactura(txtNroFactura.getText().trim());
                            }
                            item.setIdNeumatico(neumatico);
                            fila++;
                        }
                    }
                    if(estaRecepcionadoTotal(detalle)){
                        controlReencaucheRec.setEstadoTransaccion(true);
                        controlReencaucheRec.setNumFactura(txtNroFactura.getText().trim());
                        controlReencaucheRec.setFechaRecepcion(jDateFechaRec.getDate());
                        controlReencaucheRec.setEstadoTransaccion(true);
                    }
                    em.persist(controlReencaucheRec);
                    tx.commit();
                    JOptionPane.showMessageDialog(this, "La recepción se ha realizado con éxito.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(this, "La fecha de recepción no puede ser mayor que la fecha de envío a reencauche.", "Advertencia", JOptionPane.WARNING_MESSAGE);
                    jDateFechaRec.requestFocusInWindow();
                }
            } catch (Exception e) {
                em.getTransaction().rollback();
                JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            } finally {
                if (em != null) {
                    em.close();
                }
            }
        }
    }

    private boolean estaRecepcionadoTotal(List<DetalleControlReencauche> detalle){
        for(DetalleControlReencauche item : detalle){
            if(item.getFechaRecepcion() == null && item.getEstado()){
                return false;
            }
        }
        return true;
    }
    
    @Override
    public void mouseClicked(MouseEvent e) {
    }

    @Override
    public void mousePressed(MouseEvent e) {
    }

    @Override
    public void mouseReleased(MouseEvent e) {
        if (e.getSource() == textComentario) {
            DialogoIngresoObservacionES dlg = new DialogoIngresoObservacionES(Principal.getInstance(), true, textComentario.getText(), true);
            dlg.setVisible(true);
            if (dlg.OPCION == 1) {
                textComentario.setText(dlg.getMensaje());
            }
            if (jTableDetalle.getCellEditor() != null) {
                jTableDetalle.getCellEditor().stopCellEditing();
            }
        }
    }

    @Override
    public void mouseEntered(MouseEvent e) {
    }

    @Override
    public void mouseExited(MouseEvent e) {
    }
}
